package midend;

import midend.IR_Value.IR_BaseBlock;
import midend.IR_Value.IR_Value;

import java.util.HashMap;

//作用域
public class Scope {
    private Scope fatherScope;
    private String ScopeName;
    private IR_BaseBlock currentbb;
    private HashMap<String, IR_Value> currentMap;
    private int dep;

    public Scope(Scope fatherScope, String scopeName, IR_BaseBlock currentbb) {
        this.fatherScope = fatherScope;
        if(fatherScope == null){
            dep = 0;
        }
        else{
            dep = fatherScope.getDep() + 1;
        }
        ScopeName = scopeName;
        this.currentbb = currentbb;
        this.currentMap = new HashMap<>();
    }

    public int getDep(){
        return dep;
    }
    public Scope get_fatherScope() {
        return fatherScope;
    }

    public String get_ScopeName() {
        return ScopeName;
    }

    public IR_BaseBlock get_currentbb() {
        return currentbb;
    }

    public void add_var(String name,IR_Value value){
        this.currentMap.put(name,value);
    }
    public IR_Value findincurrent(String name){
        return this.currentMap.get(name);
    }
    public IR_Value findinAll(String name){
        Scope cur = this;
        while(cur != null){
            IR_Value value = cur.currentMap.get(name);
            if(value != null){
                return value;
            }
            cur = cur.fatherScope;
        }
        return null;
    }

    public IR_BaseBlock findwhile(){
        Scope current = this;
        while(current != null){
            if(current.ScopeName.contains("whilebody")){
                return current.get_currentbb();
            }
            current = current.fatherScope;
        }
        return null;
    }
}
